﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ZhuXingFamilys.ExportExcel.utils
{
	public static class HandleFiles
	{
		public static void EncryptFile(string inputFile, string outputFile)   //加密
		{
			try
			{
				string password = @"12345678";
				UnicodeEncoding UE = new UnicodeEncoding();
				byte[] key = UE.GetBytes(password);

				string cryptFile = outputFile;
				FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

				RijndaelManaged RMCrypto = new RijndaelManaged();

				CryptoStream cs = new CryptoStream(fsCrypt,
					RMCrypto.CreateEncryptor(key, key),
					CryptoStreamMode.Write);

				FileStream fsIn = new FileStream(inputFile, FileMode.Open);

				int data;
				while ((data = fsIn.ReadByte()) != -1)
					cs.WriteByte((byte)data);


				fsIn.Close();
				cs.Close();
				fsCrypt.Close();


				MessageBox.Show("导出成功", "提示");
			}
			catch (Exception ex)
			{
				throw;
				//MessageBox.Show("Source file error!", "Error :");
			}
		}

		public static void DecryptFile(string inputFile, string outputFile)   //解密
		{
			FileStream fsCrypt = null;
			CryptoStream cs = null;
			FileStream fsOut = null;
			try
			{
				// 备份原文件
				FileInfo oldpaths = new FileInfo(outputFile);
                FileInfo newpaths = null;
                if (oldpaths.Exists)
                { 
                    newpaths = oldpaths.CopyTo(outputFile + "_bak", true);
                }
                string password = @"12345678";
				UnicodeEncoding UE = new UnicodeEncoding();
				byte[] key = UE.GetBytes(password);

				fsCrypt = new FileStream(inputFile, FileMode.Open);

				RijndaelManaged RMCrypto = new RijndaelManaged();

				cs = new CryptoStream(fsCrypt,
					RMCrypto.CreateDecryptor(key, key),
					CryptoStreamMode.Read);

				fsOut = new FileStream(outputFile, FileMode.Create);

				int data;
				while ((data = cs.ReadByte()) != -1)
					fsOut.WriteByte((byte)data);

				fsOut.Close();
				cs.Close();
				fsCrypt.Close();
				// 删除备份文件
                if (newpaths != null)
                {
				    newpaths.Delete();
                }
                //MessageBox.Show("导入成功", "提示");
                fsOut.Close();
				cs.Close();
				fsCrypt.Close();
			}
			catch (Exception)
			{
				fsOut.Close();
				fsCrypt.Close();
				// 还原备份文件
				FileInfo oldpaths = new FileInfo(outputFile + "_bak");
                if (oldpaths.Exists)
                {
                    oldpaths.CopyTo(outputFile, true);
                    oldpaths.Delete();
                }
				throw;
			}
		}
	}
}
